package cn.wolfcode.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 面试题
 * 编写一个程序，开启 3 个线程，
 * 这三个线程的 ID 分别为 A、B、C，
 * 每个线程将自己的 ID 在屏幕上打印 10遍，
 * 要求输出的结果必须按顺序显示。
 * 如：ABCABCABC…… 依次递归。
 */
public class ThreadABC {
    public static void main(String[] args) {
        ABC abc = new ABC();
        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i <10 ; i++) {
                    abc.lockA();

                }
            }
        },"A").start();
        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i <10 ; i++) {
                    abc.lockB();

                }
            }
        },"B").start();
        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i <10 ; i++) {
                    abc.lockC();
                }
            }
        },"C").start();
    }
}

class ABC{
    private int num = 1;
    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();
    public void lockA(){
        lock.lock();
        try {
            if (num != 1){
                try {
                    condition1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName());
            num = 2;
            condition2.signalAll();
        }finally {
            lock.unlock();
        }

    }
    public void lockB(){
        lock.lock();
        try {
            if (num != 2){
                try {
                    condition2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName());
            num = 3;
            condition3.signalAll();
        }finally {
            lock.unlock();
        }

    }
    public void lockC(){
        lock.lock();
        try {
            if (num != 3){
                try {
                    condition3.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName());
            num = 1;
            condition1.signalAll();
        }finally {
            lock.unlock();
        }

    }
}
